<template>
  <div class="home-nav-right">
    <div class="tools-list">
      <!-- 客服 -->
      <d-tooltip position="left" overlay-class="tools-tag-tooltip">
        <div class="tools-list-item mb-[2px]">
          <div id="gitcode-desk-btn" class="home-nav-item kefu" @click="showDesk">
            <img class="inline-block h-[20px] w-[20px]" src="https://cdn-static.gitcode.com/static/images/desk/kefu.png" alt="">
            <div>
              <div>客</div>
              <div>服</div>
            </div>
          </div>
        </div>
        <template #content>
          <div class="home-nav-tooltip-wrapper">
            <div class="home-nav-text">
              <p>{{ $t('home.userFeedback01') }}</p>
              <p class="text-[#9C9DB4] text-[10px]">{{ $t('home.userFeedback02') }}</p>
            </div>
          </div>
        </template>
      </d-tooltip>
      <!-- 入驻 -->
      <!-- <d-tooltip position="left" overlay-class="tools-tag-tooltip">
        <a class="home-nav-link tools-list-item" :href="`${PrefixEmail}${contact}`">
          <div class="home-nav-item">
            <img class="common-icon inline-block h-[20px] w-[20px]"
              src="https://cdn-static.gitcode.com/static/images/desk/plane-organize-entry.png" alt="">
            <img class="active-icon inline-block h-[20px] w-[20px]"
              src="https://cdn-static.gitcode.com/static/images/desk/plane-organize-entry-hover.png" alt="">
          </div>
        </a>
        <template #content>
          <div class="home-nav-tooltip-wrapper">
            <div class="home-nav-text">
              {{ $t('home.settlementMsg') }}：<a class="home-nav-link devui-link-light"
                :href="`${PrefixEmail}${contact}`">{{ contact }}</a>
              ，{{ $t('home.settlementMsgContact') }}~
            </div>
          </div>
        </template>
      </d-tooltip> -->
      <d-tooltip position="left" overlay-class="tools-tag-tooltip">
        <a class="home-nav-link tools-list-item">
          <div class="home-nav-item">
            <img class="common-icon inline-block h-[20px] w-[20px]" src="https://cdn-static.gitcode.com/static/images/desk/follow-us.svg" alt="">
            <img class="active-icon inline-block h-[20px] w-[20px]" src="https://cdn-static.gitcode.com/static/images/desk/follow-us-hover.svg" alt="">
          </div>
        </a>
        <template #content>
          <div class="qrcode-wrapper">
            <div class="pl-[8px]">{{ $t('home.followUs') }}</div>
            <img class="qrcode" src="https://cdn-static.gitcode.com/static/images/points/wx_gitcode.png"/>
          </div>
        </template>
      </d-tooltip>
      <!-- 用户体验nps -->
      <d-popover v-if="popVisible" :offset="OffsetOptions" :position="['left']" class="no-arrow" :is-open="popVisible">
        <div class="tools-list-item">
          <div class="home-nav-item">
            <img class="common-icon inline-block h-[20px] w-[20px]"
              src="https://cdn-static.gitcode.com/static/images/desk/plane-smile.png" alt="">
            <img class="active-icon inline-block h-[20px] w-[20px]"
              src="https://cdn-static.gitcode.com/static/images/desk/plane-smile-hover.png" alt="">
          </div>
        </div>
        <template #content>
          <div class="g-card px-5 pt-4 pb-5 w-[410px]">
            <div class="opinion-box" v-if="process">
              <div class="tab-step">
                <div v-for="item in opinionStep" :key="item.index" class="tab-item w-8 h-1 mr-1 cursor-pointer"
                  :class="opStep === item.index ? 'bg-G900' : 'bg-G400'" @click="swTab(item)"><span
                    class="cursor-pointer"></span></div>
              </div>
              <div>
                <div v-if="opStep === 0" class="rate relative overflow-hidden">
                  <div v-if="rateActive !== null || rateNow !== null" class="absolute top-0 right-0 text-G900"><span>{{
                    rateIcon[rateActive === null ? rateNow :rateActive].title }}</span></div>
                  <div class="font-[600] text-G900 mt-3 text-sm leading-[20px]"><span>{{ $t('home.rateExperience')
                      }}</span></div>
                  <div class="flex gap-1 items-center mt-3">
                    <div v-for="ico in rateIcon" :key="ico.name"
                      class="opinion-item cursor-pointer border border-G300 rounded-[3px] px-2 py-1.5"
                      :class="{ active: rateNow === ico.index }" @mouseover="activeOp(ico.index)"
                      @mouseleave="activeOp(null)" @click="selOpini(ico)">
                      <GIcon :name="ico.name" size="24px" />
                    </div>
                  </div>
                </div>
                <div v-if="opStep === 1" class="Opinion relative overflow-hidden">
                  <div v-if="rateNow !== null" class="absolute top-0 right-0 text-G900"><span>{{ rateIcon[rateNow].title
                      }}</span></div>
                  <div class="font-[600] text-G900 mt-3 text-sm leading-[20px]">
                    <span>{{ $t('home.improveQuestion') }}？</span></div>
                  <div class="mt-3">
                    <d-textarea v-model="opinionText" :rows="4" :placeholder="$t('home.facebackPlaceholder')" show-count
                      maxlength="200"></d-textarea>
                  </div>
                  <div>
                    <d-button color="primary" variant="solid" @click="handleSubmit">{{ $t('repo.pr.commit')
                      }}</d-button>
                  </div>
                </div>
              </div>
            </div>
            <div class="finish flex items-center" v-else>
              <div class="flex justify-center items-center w-[30px] h-[30px] rounded-[50%] bg-[#0EB07B]">
                <GIcon name="gt-success" size="14px" color="#fff" />
              </div>
              <div class="ml-2 font-[600] text-G900 text-sm leading-[20px]"><span>{{ $t('home.thankFaceback') }}！</span>
              </div>
            </div>
          </div>
        </template>
      </d-popover>
    </div>
    <div @click="backTop" v-if="backTopVisible" class="back-top !bg-[#fff] w-[48px] h-[48px] flex items-center justify-center">
      <div>
        <GIcon name="gt-plane-Topping" class="home-nav-icon" size="20px"/>
      </div>
    </div>
    <!-- 调查问卷 25年6月30日下线 -->
    <!-- <d-tooltip position="left" overlay-class="tools-tag-tooltip">
      <a class="home-nav-link tools-questionnaire" href="https://wj.qq.com/s2/19601885/hha0/" target="_blank"
        rel="noopener noreferrer">
        <div class="home-nav-item">
          <GIcon name="gt-a-plane-questionnaireinvestigation" class="home-nav-icon" size="20px" />
        </div>
      </a>
      <template #content>
        <div class="home-nav-tooltip-wrapper">
          <div class="home-nav-text">
            <a class="home-nav-link devui-link-light" href="https://wj.qq.com/s2/19601885/hha0/" target="_blank"
              rel="noopener noreferrer">
              {{ $t('home.surveyTipsTitle') }}
            </a>
          </div>
        </div>
      </template>
    </d-tooltip> -->
  </div>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
import { reactive, ref, computed } from 'vue';
import { useReport } from '@/composables/hooks/useReport'
import { emitEvent } from '@/composables/useMitt';
import { udeskInit } from '@/utils/udesk';


udeskInit() // 执行生成客服的脚本
const contact = 'kefu@gitcode.com';
const PrefixEmail = 'mailto:';
const opinionStep = [{ index: 0, offset_x: -30 }, { index: 1, offset_x: -80 }];
const opStep = ref<number>(0);
const rateNow = ref(null);
const rateActive = ref(null);
const process = ref(true);
const popVisible = ref(true);
const opinionText = ref<string>('');
const activeJson = ref();
const rateIcon = [
  { name: 'gt-nps-1', title: t('home.veryGood'), index: 0 },
  { name: 'gt-nps-2', title: t('home.good'), index: 1 },
  { name: 'gt-nps-3', title: t('home.generally'), index: 2 },
  { name: 'gt-nps-4', title: t('home.bad'), index: 3 },
  { name: 'gt-nps-5', title: t('home.veryBad'), index: 4 }
];
const store: any = localStorage.getItem('spmStatus');
const status = store ? JSON.parse(store) : null;
if (status !== null) {
  const { nps_global } = status;
  popVisible.value = nps_global.expire && nps_global.expire < Date.now();// 过期后才能重新展示
}
const swTab = (item: any) => { // 切换步骤
  if (rateNow.value === null && item.index === 1) return;
  OffsetOptions.crossAxis = item.offset_x;
  opStep.value = item.index;
  window.dispatchEvent(new Event('resize'));// 触发更新位置
};
const activeOp = (index: any) => { // hover等级
  rateActive.value = index;
};
const selOpini = (item: any) => { // 设置等级
  rateNow.value = item.index;
  swTab(opinionStep[1]);
};
const OffsetOptions = reactive({ mainAxis: 10, crossAxis: -30 });
const handleSubmit = () => { // 提交意见
  useReport('nps_global', {
    nps_score: rateNow.value as any + 1,
    nps_comment: opinionText.value
  }).then(res => {
    process.value = false;
    OffsetOptions.crossAxis = 0;
    window.dispatchEvent(new Event('resize'));// 触发更新位置
    const nextStatus = status || {};
    nextStatus.nps_global = { expire: Date.now() + 86400000 * 15 };// 记录提交的过期时间
    localStorage.setItem('spmStatus', JSON.stringify(nextStatus));
    setTimeout(() => { popVisible.value = false; }, 500);
  });
};

// const activeItem = computed(() => {
//   if (activeJson.value?.adList.length > 0) {
//     return activeJson.value.adList.filter((item: any) => item.showThis)[0];
//   }
//   return {};
// });

// const fetchData = async () => {
//   const closeActive = localStorage.getItem('closeActive');
//   const closeDate = localStorage.getItem('closeDate');
//   const nowDate = new Date().toLocaleDateString('zh-CN');
//   if (closeActive && closeActive === '1' && closeDate === nowDate) {
//     return false;
//   }
//   const adLink = import.meta.env.VITE_AD_LINK + '?timestamp=' + new Date().getTime();
//   const response = await fetch(adLink);
//   activeJson.value = await response.json();
// };

// fetchData();

// const handleLogin = (type: string) => {
//   emitEvent('login', { type, triggerType: '免费领取云主机' });
//   localStorage.setItem('sign_path', location.href);
// };

// const handleActive = () => {
//   if (activeJson.value) {
//     const { href } = activeItem.value;

//     window.open(href as string);
//   }
// };

// const handleActiveClose = () => {
//   activeJson.value = null;
//   localStorage.setItem('closeActive', '1');
//   const dateString = new Date().toLocaleDateString('zh-CN');
//   localStorage.setItem('closeDate', dateString);
// };

// 回到顶部
const backTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}

// 是否显示回到顶部按钮
const backTopVisible = ref(false);
const handleScroll = () => {
  backTopVisible.value = window.scrollY > 300;
};
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  });
};

onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll);
});

</script>

<style scoped lang="scss">
.qrcode-wrapper {
  padding: 14px 12px;
  font-size: 12px;
  font-weight: 600;
}
.qrcode {
  width: 146px;
  height: 146px;
}
.home-nav-right {
  position: fixed;
  right: 16px;
  bottom: 64px;
  z-index: 20;
  display: flex;
  flex-direction: column;
  pointer-events: none;
  @media screen and (max-width: $screen-md) { // 小屏不显示工具栏
    display: none;
  }
  .tools-list {
    pointer-events: auto;
    margin-top: 10px;
    margin-left: auto;
    padding: 6px 0;
    border-radius: 48px;
    background: #fff;
    box-shadow: 0px 8px 24px 0px #0000001F;
  }
  .home-nav-item {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    text-align: center;
    line-height: 33px;
    &.kefu {
      background: linear-gradient(128.22deg, #FF8E55 9.27%, #E93F5C 68.77%);
      height: 80px;
      border-radius: 36px;
      width: 36px;
      div {
        font-size: 14px;
        font-weight: 600;
        text-align: center;
        color: #fff;
        line-height: 1.35;
      }
    }
  }

  .active-tips{
    position: relative;
    cursor: pointer;

    .close-btn {
      position: absolute;
      width: 30px;
      height: 30px;
      right: 0px;
      top: 0px;
      cursor: pointer;
    }
  }
}

.home-nav-tooltip-wrapper {
  padding: 6px 12px;
  max-width: 190px;
  font-size: 12px;
  line-height: 18px;
  @apply whitespace-normal break-all;
  a.link-kefu {
    display: inline-block;
  }
}
.home-nav-link {
  color: rgba(59, 130, 246, 1);
  cursor: pointer;
  display: flex;
  margin-left: auto;
}

.tools-list-item {
  padding: 0 6px;
  border-radius: 50%;

  .active-icon {
    display: none;
  }

  &:hover {
    .home-nav-item {
      cursor: pointer;
      background: linear-gradient(128.22deg, rgba(255, 142, 85, 0.1) 9.27%, rgba(218, 31, 63, 0.1) 68.77%);
    }
    .home-nav-item.kefu {
      cursor: pointer;
      background: linear-gradient(128.22deg, #FF8E55 9.27%, #E93F5C 68.77%);
    }

    .common-icon {
      display: none;
    }

    .active-icon {
      display: inline-block;
    }
  }
}

.tools-questionnaire {
  margin-top: 10px;
  padding: 6px;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0px 8px 24px 0px #0000001F;
  text-align: center;
  pointer-events: auto;
  .home-nav-item {
    line-height: 34px;
  }
}
.opinion-box {
  display: flex;
  flex-direction: column;

  .tab-step {
    display: flex;

    .tab-item {
      border-radius: 2px;
      position: relative;

      span {
        width: 100%;
        height: 12px;
        position: absolute;
        top: -4px;
        left: 0;
        z-index: 1;
      }
    }
  }

  .rate {
    .opinion-item {
      width: 40px;
      height: 36px;

      &:hover,
      &.active {
        background: var(--color-B500);
        border-color: transparent;

        .icon {
          color: #fff !important;
        }
      }
    }
  }
}

// 工具栏深色
.home-nav-dark {

  .tools-list,
  .tools-questionnaire {
    background-color: #30363D;
  }

  .tools-list {
    .home-nav-item {
      &:hover {
        background: linear-gradient(128.22deg, rgba(255, 142, 85, 0.32) 9.27%, rgba(218, 31, 63, 0.32) 68.77%);
      }
    }
  }
}

.back-top {
  padding: 16px;
  box-shadow: 0px 8px 24px 0px rgba(0, 0, 0, 0.12);
  border-radius: 48px;
  pointer-events: auto;
  cursor: pointer;
  margin-top: 16px;
}
</style>
<style lang="scss">
.no-arrow {
  &.devui-popover__content.devui-flexible-overlay {
    background: #fff;
    padding: 0;
    border: none;
    box-shadow: none;
  }

  .devui-flexible-overlay__arrow {
    display: none !important;
  }
}

body .devui-tooltip.tools-tag-tooltip {
  background-color: #fff;
  color: #3B3E55;
}

// 工具栏深色
body .devui-tooltip.tools-tag-tooltip-dark {
  background-color: #30363D;
}
</style>
